#!/bin/bash
#
# Detects OS we're compiling on and outputs a file specified by the first
# argument, which in turn gets read while processing Makefile.
#
# The output will set the following variables:
#   CC                          C Compiler path
#   CXX                         C++ Compiler path
#   PLATFORM_CFLAGS             C compiler flags
#   PLATFORM_CXXFLAGS           C++ compiler flags
#   PLATFORM_CFLAGS_SHARED      Flags for compiling objects for shared library
#   PLATFORM_LDFLAGS            Flags for building binaries
#   PLATFORM_LDFLAGS_SHARED     Flags for building shared library
#   FOLLY_ROOT                  Directory with folly source (already configure-d)

OUTPUT=$1
if test -z "$OUTPUT"; then
  echo "usage: $0 <output-filename>" >&2
  exit 1
fi
rm -f "$OUTPUT"

FBCODE_CONFIG_SCRIPT="$(dirname $0)/../fb/fbcode_build_config.py"
if test -z "$LOGDEVICE_NO_FBCODE" -a -x "$FBCODE_CONFIG_SCRIPT"; then
    # Default to fbcode toolchain (gcc, third party) on internal fb machines
    output=$("$FBCODE_CONFIG_SCRIPT") || exit 1
    eval $output
else
    # Use system libraries
    BOOST_LIBS=$(echo -lboost_{thread,regex,filesystem,chrono,system,program_options})
    PLATFORM_LDFLAGS=" $PLATFORM_LDFLAGS $BOOST_LIBS -levent -levent_openssl -lsnappy -lz -lbz2 -llz4 -lzstd -lzookeeper_mt -lnuma -lglog -lgflags -ltbb -llzma -ldouble-conversion -ljemalloc -ldwarf -liberty -lunwind -lelf -ldl -lssl -lcrypto"
    PLATFORM_LDFLAGS_SHARED="$PLATFORM_LDFLAGS"
    FOLLY_ROOT="$(dirname $0)/../external/folly/folly"
    ROCKSDB_ROOT="$(dirname $0)/../../external/rocksdb"
    COMMON_FLAGS="-I$(dirname $FOLLY_ROOT)"
fi

test -z "$AR" && AR=ar
test -z "$CC" && CC=cc
test -z "$CXX" && CXX=g++

# TODO optimization flags? (e.g. -march)

PLATFORM_CFLAGS_SHARED="-fPIC"
PLATFORM_LDFLAGS="$PLATFORM_LDFLAGS -lpthread -lrt"
PLATFORM_LDFLAGS_SHARED="$PLATFORM_LDFLAGS_SHARED -Wl,--no-as-needed -shared"

cat <<EOF >"$OUTPUT"
CC=$CC
CXX=$CXX
AR=$AR
PLATFORM_CFLAGS=$COMMON_FLAGS $PLATFORM_CFLAGS
PLATFORM_CXXFLAGS=$COMMON_FLAGS $PLATFORM_CXXFLAGS
PLATFORM_CFLAGS_SHARED=$PLATFORM_CFLAGS_SHARED
PLATFORM_LDFLAGS=$PLATFORM_LDFLAGS
PLATFORM_LDFLAGS_SHARED=$PLATFORM_LDFLAGS_SHARED
FOLLY_ROOT=$FOLLY_ROOT
ROCKSDB_ROOT=$ROCKSDB_ROOT
EOF
